package net.interest.curation;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpSession;

import net.interest.curation.model.SocialUser;
import net.interest.curation.model.User;
import net.interest.curation.service.FacebookService;
import net.interest.curation.service.TwtService;

import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import scenic3.ScenicPage;
import scenic3.annotation.ActionPath;
import scenic3.annotation.Page;

@Page("/auth")
public class AuthenticationPage extends ScenicPage {
    private static final Logger log =
        Logger.getLogger(AuthenticationPage.class.getName());
    
    private static final TwtService TWT_SERVICE = new TwtService();
    private static final FacebookService FB_SERVICE = new FacebookService();

    // /
    @ActionPath("login")
    public Navigation login() {
        return forward("/auth/login.jsp");
    }
    
    @ActionPath("logout")
    public Navigation logout() {
        request.getSession().invalidate();
        return forward("/auth/login.jsp");
    }
    
    @ActionPath("login/twt")
    public Navigation loginTwt(){
        
        final StringBuffer requestURL = request.getRequestURL();
        final int index = requestURL.lastIndexOf("/");
        String callbackURL = String.format("%s/" + "twt/callback", requestURL.replace(index, requestURL.length(), ""));

        String isAdd = request.getParameter("add");
        if(isAdd != null)
            callbackURL += "?add=true";
        
        String authorizeURL = TWT_SERVICE.getAuthorizeUrl(request, callbackURL);
        return redirect(authorizeURL);
    }
    
    @ActionPath("login/twt/callback")
    public Navigation loginTwtCallback() {
        try {
            String requestToken = (String) request.getSession().getAttribute("requestToken");
            String requestTokenSecret = (String) request.getSession().getAttribute("requestTokenSecret");
            
            SocialUser socialUser = TWT_SERVICE.getAuthorizedUser(requestToken, requestTokenSecret);
            System.out.println("****************" + socialUser);
            HttpSession session = super.request.getSession(true);
            
            User sessionUser = (User) session.getAttribute(User.SESSION_USER_ATTR_NAME);

            if(socialUser.getUserRef().getModel() == null){
                User user = sessionUser;
                if(user == null){
                    user = User.createUser();
                }
                log.info("New user set twitter user: " + socialUser);
                socialUser.getUserRef().setModel(user);
                Datastore.put(socialUser);
            }
            
            if(sessionUser == null){
                sessionUser = socialUser.getUserRef().getModel();
                session.setAttribute(User.SESSION_USER_ATTR_NAME, sessionUser);
            }

            String isAdd = request.getParameter("add");
            if(isAdd != null)
                return forward("/auth/callback.jsp");
            else
                return redirect("/");
         
        } catch (IOException e) {
            log.severe(e.getLocalizedMessage());
            return forward("error.jsp");//TODO:
        }
    }

    @ActionPath("login/fb")
    public Navigation loginFb() {
        String isAdd = request.getParameter("add");
        String callbackurl = request.getScheme() + "://" + request.getServerName() + (request.getServerPort() > 80 ?  ":" + request.getServerPort() : "") + "/auth/login/fb/callback";
        if(isAdd != null) callbackurl += "?add=true";
        try {
            return redirect(FB_SERVICE.getAuthorizeUrl(request, callbackurl));
        } catch (IOException e) {
            log.severe(e.getLocalizedMessage());
            return forward("error.jsp");//TODO:
        }
    }

    @ActionPath("login/fb/callback")
    public Navigation callback() {
        try {
            String token = request.getParameter("code");
            
            String redirectUrl = request.getScheme() + "://" + request.getServerName() + (request.getServerPort() > 80 ?  ":" + request.getServerPort() : "") + "/auth/login/fb/callback";
            String isAdd = request.getParameter("add");
            if(isAdd != null) redirectUrl += "?add=true";
            
            SocialUser socialUser = FB_SERVICE.getAuthorizedUser(token, redirectUrl);

            HttpSession session = super.request.getSession(true);

            User sessionUser = (User) session.getAttribute(User.SESSION_USER_ATTR_NAME);
            
            if(socialUser.getUserRef().getModel() == null){
                User user = sessionUser;
                if(user == null){
                    user = User.createUser();
                }
                log.info("New user set facebook user: " + socialUser);
                socialUser.getUserRef().setModel(user);
                Datastore.put(socialUser);
            }
            
            if(sessionUser == null){
                sessionUser = socialUser.getUserRef().getModel();
                session.setAttribute(User.SESSION_USER_ATTR_NAME, sessionUser);
            }

            if(isAdd != null)
                return forward("/auth/callback.jsp");
            else
                return redirect("/");
         
        } catch (IOException e) {
            log.severe(e.getLocalizedMessage());
            return forward("error.jsp");//TODO:
        }
    }
    
}